package com.bnz.search.utils;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.BulkRequest;
import co.elastic.clients.elasticsearch.core.DeleteByQueryRequest;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bnz.search.dao.ItemDao;
import com.bnz.search.entity.ItemEntity;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 类名：
 * 作者：WF
 * 功能：ES7.16之后的版本
 */
@SpringBootTest
public class ESUtil {

    @Autowired
    private ElasticsearchClient client;
    @Autowired
    private ItemDao itemDao;
    /**
     * 1. 创建索引库
     */
    @Test
    public void test01() throws IOException {
        client.indices().create(idx->idx.index("item")
                .mappings(mappingBuilder->mappingBuilder
                        .properties("title",propertyBuilder->propertyBuilder.text(textProperty->textProperty.analyzer("ik_smart").searchAnalyzer("ik_smart")))
                        // .properties("title",propertyBuilder->propertyBuilder.text(textProperty->textProperty))
                        .properties("price",propertyBuilder->propertyBuilder.float_(floatProperty->floatProperty))
                        .properties("category",propertyBuilder->propertyBuilder.keyword(keywordProperty->keywordProperty))
                        .properties("brand",propertyBuilder->propertyBuilder.keyword(brandProperty->brandProperty))
                ));
    }
    /**
     * 2. 添加数据到索引库
     */
    @Test
    public void test02() throws IOException {
        //2.1 查询经审核通过后的商品
        List<ItemEntity> itemEntities = itemDao.selectList(new QueryWrapper<ItemEntity>().eq("status", "1"));
        //2.2 处理上面的数据
        for (ItemEntity item : itemEntities) {
            //2.2.1 得到规格值
            String spec = item.getSpec();
            //2.2.2 将规格值转换为map对象
            Map map = JSON.parseObject(spec, Map.class);
            //2.2.3 将此map直接赋值给specMap
            item.setSpecMap(map);
        }
        //2.3 将商品放到索引库中
        BulkRequest.Builder br = new BulkRequest.Builder();
        for (ItemEntity item : itemEntities) {
            br.operations(option->option
                    .index(idx->idx
                            .index("item")
                            .id(item.getId()+"")
                            .document(item)));
        }
        BulkRequest build = br.build();
        client.bulk(build);
    }

    /**
     * 根据goodsId来删除指定记录
     * @throws IOException
     */
    @Test
    public void test03() throws IOException {
        Long id = 1588730097213054977L;
        client.deleteByQuery(d ->d.index("item").query(q -> q.term(t->t.field("goodsId").value(id))));
    }
}
